package logger

import (
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
	"time"
	"wzgames/pkg/config"
)

type IAdapterWriter interface {
	Name() string
	Write(p []byte) (n int, err error)
	Ok() bool
}

func myZapLogger(conf *LoggerConfig, options ...zap.Option) {
	level := toZapLevel(conf.Level)
	wzgl := &WZGLogger{level: zap.NewAtomicLevelAt(level), conf: conf}
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	encoderConfig.EncodeTime = func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
		enc.AppendString(t.Format("2006-01-02 15:04:05.000"))
	}

	var encoder zapcore.Encoder
	if conf.Encoding == "json" {
		encoder = zapcore.NewJSONEncoder(encoderConfig)
	} else {
		encoder = zapcore.NewConsoleEncoder(encoderConfig)
	}
	core := zapcore.NewCore(
		encoder,
		zapcore.AddSync(wzgl),
		wzgl.level,
	)
	wzgl.zapLogger = zap.New(core, options...)
	wzgl.zapSuger = wzgl.zapLogger.Sugar()

	lg = wzgl

	if conf.Writers == nil || conf.Writers.FileConf == nil {
		stdZapLogger(options...)
	} else {
		fileConf := &config.YAMLConfData{}
		fileConf.ReplaceData(conf.Writers.FileConf)

		compress, _ := fileConf.GetBool("compress")
		localTime, _ := fileConf.GetBool("local_time")
		filepath := fileConf.GetString("filepath", "logs/")
		wzgl.fileWriter = &lumberjack.Logger{
			Filename:   filepath + fileConf.GetString("filename", "log.txt"),
			MaxSize:    fileConf.GetInt("max_size", 1),
			MaxBackups: fileConf.GetInt("max_backups", 5),
			MaxAge:     fileConf.GetInt("max_age", 30),
			Compress:   compress,
			LocalTime:  localTime,
		}
	}
}

func SetMQWriter(mqw IAdapterWriter) {
	lg.mqWriter = mqw
}

func (l *WZGLogger) Write(p []byte) (n int, err error) {
	if l.mqWriter != nil && l.mqWriter.Ok() {
		return l.mqWriter.Write(p)
	}

	if l.fileWriter != nil {
		return l.fileWriter.Write(p)
	}

	return 0, nil
}
